package com.betty.cscams.service.impl;

import java.io.File;
import java.util.*;

import com.betty.cscams.common.exception.CscaException;
import com.betty.cscams.common.page.MybatisPageHelper;
import com.betty.cscams.common.page.PageRequest;
import com.betty.cscams.common.page.PageResult;
import com.betty.cscams.dao.*;

import com.betty.cscams.entity.*;
import com.betty.cscams.service.SysMenuService;
import com.betty.cscams.service.SysUserService;
import com.betty.cscams.util.PasswordUtils;
import com.betty.cscams.util.SecurityUtils;
import com.betty.cscams.vo.UserInfoBean;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
public class SysUserServiceImpl  implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	@Autowired
	private SysRoleMapper sysRoleMapper;
	@Autowired
	private SysUserDeptMapper sysUserDeptMapper;
	@Autowired
	private BusUserSubjectMapper busUserSubjectMapper;

	@Autowired
	private BusExpandMapper busExpandMapper;
	@Autowired
	private BusMoralMapper busMoralMapper;
	@Autowired
	private BusScoreMapper busScoreMapper;
	@Autowired
	private BusSynthesisMapper busSynthesisMapper;

	@Transactional
	@Override
	public int save(SysUser record) {
		Long id = null;
		record.setLastUpdateBy(SecurityUtils.getUsername());
		record.setLastUpdateTime(new Date());
		if(record.getId() == null || record.getId() == 0) {
			record.setCreateBy(SecurityUtils.getUsername());
			record.setCreateTime(new Date());
			record.setStatus((byte) 2);
			// 新增用户
			sysUserMapper.insertSelective(record);
			id = record.getId();
		} else {
			// 更新用户信息
			sysUserMapper.updateByPrimaryKeySelective(record);
		}
		// 更新用户角色
		if(id != null && id == 0) {
			return 1;
		}
		if(id != null) {
			for(SysUserRole sysUserRole:record.getUserRoles()) {
				sysUserRole.setUserId(id);
			}
		} else {
			sysUserRoleMapper.deleteByUserId(record.getId());
			busUserSubjectMapper.deleteByUserId(record.getId());
		}
		for(SysUserRole sysUserRole:record.getUserRoles()) {
			sysUserRoleMapper.insertSelective(sysUserRole);
		}
		List<BusUserSubject> list = record.getSubjects();
		if(list != null && !list.isEmpty()){
			for (BusUserSubject object:list) {
				busUserSubjectMapper.add(object);
			}
		}
		return 1;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int delete(SysUser record) {
		SysUser sysUser = findById(record.getId());
		busExpandMapper.deleteByStudent(sysUser.getName());
		busMoralMapper.deleteByStudent(sysUser.getName());
		busScoreMapper.deleteByStudent(sysUser.getName());
		busSynthesisMapper.deleteByStudent(sysUser.getName());
		return sysUserMapper.deleteByPrimaryKey(record.getId());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int delete(List<SysUser> records) {
		for(SysUser record:records) {
			SysUser sysUser = findById(record.getId());
			busExpandMapper.deleteByStudent(sysUser.getName());
			busMoralMapper.deleteByStudent(sysUser.getName());
			busScoreMapper.deleteByStudent(sysUser.getName());
			busSynthesisMapper.deleteByStudent(sysUser.getName());
			delete(record);

		}
		return 1;
	}

	@Override
	public SysUser findById(Long id) {
		return sysUserMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public SysUser findByName(String name) {
		return sysUserMapper.findByName(name);
	}
	
	@Override
	public PageResult findPage(PageRequest pageRequest) {
		PageResult pageResult = null;
		Object name = pageRequest.getParam("name");
		Object type = pageRequest.getParam("type");
		Object deptId =ObjectUtils.isEmpty(pageRequest.getParam("deptId"))?"": pageRequest.getParam("deptId").toString();
		if(ObjectUtils.isNotEmpty(name)) {
				pageResult = MybatisPageHelper.findPage(pageRequest, sysUserMapper, "findPageByName", name, type,deptId);
		} else {
			pageResult = MybatisPageHelper.findPage(pageRequest, sysUserMapper,"findPage",type,deptId);
		}
		// 加载用户角色信息
		findUserRoles(pageResult);
		return pageResult;
	}
	
	/**
	 * 加载用户角色
	 * @param pageResult
	 */
	private void findUserRoles(PageResult pageResult) {
		List<?> content = pageResult.getContent();
		for(Object object:content) {
			SysUser sysUser = (SysUser) object;
			List<SysUserRole> userRoles = findUserRoles(sysUser.getId());
			sysUser.setUserRoles(userRoles);
			sysUser.setRoleNames(getRoleNames(userRoles));
			if("teacher".equals(sysUser.getType())){
				List<BusUserSubject> subjects = busUserSubjectMapper.findListByUserId(sysUser.getId());
				sysUser.setSubjects(subjects);
			}
		}
	}

	private String getRoleNames(List<SysUserRole> userRoles) {
		StringBuilder sb = new StringBuilder();
		for(Iterator<SysUserRole> iter = userRoles.iterator(); iter.hasNext();) {
			SysUserRole userRole = iter.next();
			SysRole sysRole = sysRoleMapper.selectByPrimaryKey(userRole.getRoleId());
			if(sysRole == null) {
				continue ;
			}
			sb.append(sysRole.getRemark());
			if(iter.hasNext()) {
				sb.append(", ");
			}
		}
		return sb.toString();
	}

	@Override
	public Set<String> findPermissions(String userName) {	
		Set<String> perms = new HashSet<>();
		List<SysMenu> sysMenus = sysMenuService.findByUser(userName);
		for(SysMenu sysMenu:sysMenus) {
			if(sysMenu.getPerms() != null && !"".equals(sysMenu.getPerms())) {
				perms.add(sysMenu.getPerms());
			}
		}
		return perms;
	}

	@Override
	public List<SysUserRole> findUserRoles(Long userId) {
		return sysUserRoleMapper.findUserRoles(userId);
	}

	@Override
	public int saveUserDept(List<SysUserDept> records) {
		if(records == null || records.isEmpty()) {
			return 1;
		}
		Long userId = records.get(0).getUserId();
		sysUserDeptMapper.deleteByUserId(userId);
		for(SysUserDept record:records) {
			sysUserDeptMapper.add(record);
		}
		return 1;
	}

	@Override
	public List<SysUser> findUserOptions() {
		SysUser sysUser = sysUserMapper.findByName(SecurityUtils.getUsername());
		return sysUserMapper.findUserOptions(sysUser.getId(),sysUser.getType());
	}

	@Override
	public List<SysUser> findAuditOptions() {
		SysUser sysUser = sysUserMapper.findByName(SecurityUtils.getUsername());
		String type = "";
//		if("classAdmin".equals(sysUser.getType())){
//			type = "collegeAdmin";
//		}else if("student".equals(sysUser.getType()) || "teacher".equals(sysUser.getType())){
//			type = "classAdmin";
//		}
		return sysUserMapper.findByType(type);
	}

	@Override
	public int updatePassword(String password, String newPassword) {
		SysUser sysUser = sysUserMapper.findByName(SecurityUtils.getUsername());
		if(!PasswordUtils.matches(sysUser.getSalt(),password,sysUser.getPassword())){
			throw new CscaException("密码错误");
		}
		SysUser user = new SysUser();
		user.setStatus((byte) 1);
		user.setId(sysUser.getId());
		String salt  = PasswordUtils.getSalt();
		user.setSalt(salt);
		user.setPassword(PasswordUtils.encode(newPassword,salt));
		sysUserMapper.updateByPrimaryKeySelective(user);
		return 1;
	}

	@Override
	public int updatePersonInfo(UserInfoBean userInfo) {
		return sysUserMapper.updatePersonInfo(userInfo);
	}



}
